
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion

namespace ScrollingA2DBackground
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        ContentManager content;

        //The 2D textures for the background
        //Texture2D[] mBackgroundTexture = new Texture2D[5];
        Texture2D playerTexture;

        int temp;

        int totalTime;

        int currDiffenrence;

        int lastReading;

        float timeSpace;

        int animationCounter;

        //The object to draw the sprites 
        SpriteBatch mSpriteBatch;
        //int playerXPos = 0;
        //int playerYPos = 0;
        //int playerXVel = 5;
        //int playerYVel = 5;

        Vector2 position;
        Vector2 velocity;

        //My background object that will draw the background of the game
        Background background;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            content = new ContentManager(Services);
            this.temp = 0;
            this.timeSpace = 1000.0f;
            this.lastReading = 0;
            this.currDiffenrence = 0;
            this.totalTime = 0;
        }


        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }


        /// <summary>
        /// Load your graphics content.  If loadAllContent is true, you should
        /// load content from both ResourceManagementMode pools.  Otherwise, just
        /// load ResourceManagementMode.Manual content.
        /// </summary>
        /// <param name="loadAllContent">Which type of content to load.</param>
        protected override void LoadGraphicsContent(bool loadAllContent)
        {
            if (loadAllContent)
            {
                // TODO: Load any ResourceManagementMode.Automatic content
                LoadResources();
            }

            // TODO: Load any ResourceManagementMode.Manual content
        }

        void LoadResources()
        {
            //Load the image into the texture object
            //create the background object by giving the names of the backgrounds and the boundaries
            //the client window ( width, height )

            int[] dim = { this.Window.ClientBounds.Width, this.Window.ClientBounds.Height };

            string[] backNames = { "Background1", "Background2", "Background3", "Background4", "Background5" };

            background = new Background(backNames, dim);

            background.LoadGraphicsContent(content);

            this.position = Vector2.Zero;

            this.velocity = new Vector2(5.0f, 4.0f);


            //Here we place the loadGraphics method of each other background/sprite

            //player and other sprites .loadGraphicscontent( content )

            //Load the image into the texture object
            //mBackgroundTexture[0] = content.Load<Texture2D>("Background1") as Texture2D;
            //mBackgroundTexture[1] = content.Load<Texture2D>("Background2") as Texture2D;
            //mBackgroundTexture[2] = content.Load<Texture2D>("Background3") as Texture2D;
            //mBackgroundTexture[3] = content.Load<Texture2D>("Background4") as Texture2D;
            //mBackgroundTexture[4] = content.Load<Texture2D>("Background5") as Texture2D;

            playerTexture = content.Load<Texture2D>("airconman") as Texture2D;

            //Set the starting "X" position for each of the background
            //mBackground1X = 0;
            //mBackground2X = this.Window.ClientBounds.Width;
            //mBackground3X = this.Window.ClientBounds.Width * 2;
            //mBackground4X = this.Window.ClientBounds.Width * 3;
            //mBackground5X = this.Window.ClientBounds.Width * 4;


            //Initialze the sprite batch object. This will be used to draw the sprite
            mSpriteBatch = new SpriteBatch(graphics.GraphicsDevice);
        }


        /// <summary>
        /// Unload your graphics content.  If unloadAllContent is true, you should
        /// unload content from both ResourceManagementMode pools.  Otherwise, just
        /// unload ResourceManagementMode.Manual content.  Manual content will get
        /// Disposed by the GraphicsDevice during a Reset.
        /// </summary>
        /// <param name="unloadAllContent">Which type of content to unload.</param>
        protected override void UnloadGraphicsContent(bool unloadAllContent)
        {
            if (unloadAllContent == true)
            {
                content.Unload();
            }
        }


        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the default game to exit on Xbox 360 and Windows
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            this.background.Update(gameTime);
            UpdateBackgrounds();

            base.Update(gameTime);
        }



        protected void UpdateBackgrounds()
        {

            KeyboardState kState = Keyboard.GetState();
            Keys[] currKeys = kState.GetPressedKeys();

            //Move the first background, scrolling it from right to the left of the screen            
            // Check the array of pressed keys to see if the left and right keys have been pressed

            if (kState.IsKeyDown(Keys.Left))
            {
                this.position.X -= this.velocity.X;
            }

            if (kState.IsKeyDown(Keys.Right))
            {
                this.position.X += this.velocity.X;
            }

            if (kState.IsKeyDown(Keys.Down))
            {
                this.position.Y += this.velocity.Y;
            }

            if (kState.IsKeyDown(Keys.Up))
            {
                this.position.Y -= this.velocity.Y;
            }

            if (this.position.X < 0)
            {
                this.position.X = 0;
            }


            if ((this.position.Y + playerTexture.Height) > this.Window.ClientBounds.Height)
            {
                this.position.Y -= this.velocity.Y;
            }


            if (this.position.Y < 0)
            {
                this.position.Y = 0;
            }


            if (this.position.X > this.Window.ClientBounds.Width * 7 / 8)
            {
                this.position.X -= this.velocity.X;

                // If the position of the player is >= of 2/3 of the client screen,
                //then move then move the background at the speed of the player

                //moveBackground();
            }

        }



        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //Update total time run up to this point
            this.totalTime = gameTime.TotalGameTime.Milliseconds;
            
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            //Begin drawing the scene. Using AlphaBlend as the blend mode will use the transparencies of the images drawn.
            mSpriteBatch.Begin(SpriteBlendMode.AlphaBlend);


            //Draws the background jpegs in their current position, Rectangle( initial x, initial y, width, height);
            for (int i = 0; i < this.background.BackgroundNames.Length; i++)
            {


                mSpriteBatch.Draw(this.background.backTexture[i], new Rectangle(this.background.xPositions[i], 0, this.background.Dimension[0], this.background.Dimension[1]), Color.White);
            }

            //Make sure that we don't get negative values
            if (this.lastReading >= 1000 || this.lastReading > this.totalTime)
            {
                this.lastReading = 0;
                this.temp++;
            }


            //Make sure that everytime we draw, we draw the new picture at 500 milliseconds intervals
            this.currDiffenrence = this.totalTime - this.lastReading;

            //Makes sure that it displays a frame every 80 milliseconds
            if (this.currDiffenrence >= 80)
            {
                this.temp++;
                this.lastReading = this.totalTime;
                this.currDiffenrence = 0;
            }

            //Make sure to wrap around the loop array of movements.
            if (this.temp > 5 || this.temp < 0 )
            {
                this.temp = 0;
            }

            //draws the current step in the animation process
            this.mSpriteBatch.Draw(this.playerTexture, new Rectangle((int)this.position.X, (int)this.position.Y, playerTexture.Width / 6, playerTexture.Height), new Rectangle((playerTexture.Width * this.temp) / 6, 0, playerTexture.Width / 6, playerTexture.Height), Color.White);

            //Display the * value * in the window title.
            Window.Title = Convert.ToString( this.currDiffenrence );

            //End drawing the scene
            mSpriteBatch.End();
            
            //
            base.Draw(gameTime);
        }
    }
}